<template>
  <div class="message">
    <el-badge :value="MessageBoxState.noticeCount">
      <jxtech-svg-icon
        icon="#icon-xitongxiaoxishezhi"
        :size="22"
        class="pointer"
        @click="MessageBoxState.openDrawer"
      ></jxtech-svg-icon>
    </el-badge>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, Ref, watch, nextTick, onMounted } from "vue";
import mittBus from "@/utils/mittBus";
import { Client } from "@stomp/stompjs";
import { SYSTEM_CONFIG } from "@/config/system";
import { useUserStore } from "@/stores/modules/user";
import { useSysconfigrStore } from "@/stores/modules/sysconfig";
import messageMessageServiceApi from "@/api/modules/message/bean/message";
import workFlowWorkflowServiceApi from "@/api/modules/workflow/bean/workflow";

const userStore = useUserStore();
const sysConfigState = useSysconfigrStore();

/**消息框 */
const MessageBoxState = reactive({
  visible: false,
  noticeCount: 0,
  msgCount: 0,
  pendCount: 0,
  openDrawer: () => {
    mittBus.emit("openMessageDrawer");
  }
});

const WebSocketState = reactive({
  stompClient: null as any,
  initWebSocket() {
    WebSocketState.connection();
  },
  connection() {
    if (!userStore.userId) return;

    const wsUri =
      (document.location.protocol == "https:" ? "wss://" : "ws://") +
      (document.location.hostname === "" ? "localhost" : document.location.hostname) +
      ":" +
      (document.location.port === "" ? "80" : document.location.port);
    const brokerURL = wsUri + SYSTEM_CONFIG.BASE_URL + sysConfigState.websocketPath;

    WebSocketState.stompClient = new Client({
      brokerURL: brokerURL,
      connectHeaders: { Authorization: userStore.userId },
      debug: function (str) {
        // console.log("🌐 ~ file: stompjs.js:19 ~ setActivate ~ str:", str);
      },
      reconnectDelay: 10000, //重连时间
      heartbeatIncoming: 25000,
      heartbeatOutgoing: 25000
    });

    /**建立连接，订阅主题 */
    WebSocketState.stompClient.onConnect = (frame: any) => {
      // console.log("🌐 ~ file: frame.js:19 ~ setActivate ~ str:", frame);
      WebSocketState.stompClient.subscribe("/user/topic", (val: any) => {
        const data = JSON.parse(val.body);
        // console.log("data===", data);
        var dataType = data["type"];
        var message = Number(data["message"]);
        // if (message > 99) {
        //   message = '99+';
        // }
        // console.log('收到', dataType, '类型消息【', message, '】')
        // console.log('dataType===', dataType) // MESSAGE
        switch (dataType) {
          case "undefined":
            console.log("非法消息类型!");
            break;
          case "TODO":
            MessageBoxState.pendCount = message;
            MessageBoxState.noticeCount = MessageBoxState.pendCount + MessageBoxState.msgCount;
            // console.log('message===', message)
            // _self.todoCount = message
            break;
          case "MESSAGE":
            MessageBoxState.msgCount = message;
            MessageBoxState.noticeCount = MessageBoxState.pendCount + MessageBoxState.msgCount;
            //_self.messageCount = message
            break;
        }
      });
      if (sysConfigState.messageExist) messageMessageServiceApi.initMessage();
      if (sysConfigState.workflowExist) workFlowWorkflowServiceApi.initMessage();
    };

    WebSocketState.stompClient.onStompError = function (frame: any) {
      console.log("🐛Broker reported error: " + frame.headers["message"]);
      console.log("🐛Additional details: " + frame.body);
      //这里不需要重连了，新版自带重连
    };

    //启动
    WebSocketState.stompClient.activate();
  }
});

onMounted(() => {
  WebSocketState.initWebSocket();
});

mittBus.on("changeNoticeCount", (count: number) => {
  MessageBoxState.noticeCount = count;
});
</script>

<style scoped lang="scss"></style>
